import React, { useEffect, useState } from "react";
import CateProductItem from "components/cate-product-item";
import { getCategoryList, getCategoryProduct } from "network/Category";
import "./index.less";

function index() {
    const [currentIndex, setCurrentIndex] = useState("1");
    const [categoryList, setCategoryList] = useState([]);
    const [cateProductList, setCateShopList] = useState([]);

    useEffect(async () => {
        const {
            data: { categoryInfo },
        } = await getCategoryList({ channelId: null, isWholeSale: 0 });
        setCategoryList(categoryInfo);

        // 获取第一个分类的数据
        const {
            data: { commodityInfo },
        } = await getCategoryProduct({
            catKey: categoryInfo[0].code,
            ceoStatus: 0,
            channelId: null,
            page: 1,
            pageSize: 1000,
        });
        setCateShopList(commodityInfo);
    }, []);

    // 左侧tab切换
    const tabClick = async (code) => {
        setCurrentIndex(code);
        const {
            data: { commodityInfo },
        } = await getCategoryProduct({
            catKey: code,
            ceoStatus: 0,
            channelId: null,
            page: 1,
            pageSize: 1000,
        });
        setCateShopList(commodityInfo);
    };

    const cateList = categoryList.map((item) => {
        return (
            <li
                className={currentIndex === item.code ? "active" : ""}
                key={item.code}
                onClick={() => tabClick(item.code)}
            >
                {item.displayName}
            </li>
        );
    });

    return (
        <div className="category-container">
            <ul className="left-nav">{cateList}</ul>
            <div className="right-content">
                <CateProductItem cateProductList={cateProductList} />
            </div>
        </div>
    );
}

export default index;
